const express = require('express');
const cors = require('cors');
const fs = require('fs');
const https = require('https');
const path = require('path');
const { expressjwt } = require("express-jwt");
const whiteApi = require('./router/whiteApi')

const privateCrt = fs.readFileSync(path.join(process.cwd(), 'https/wangmiao888.com_bundle.crt'), 'utf8');
const privateKey = fs.readFileSync(path.join(process.cwd(), 'https/wangmiao888.com.key'), 'utf8');
const HTTPS_OPTIONS = {
  key: privateKey,
  cert: privateCrt
};

const app = express();

// 使用 CORS 中间件
app.use(cors());

// 解析 JSON 格式的请求体
app.use(express.json());
// 解析 URL 编码的请求体
app.use(express.urlencoded({ extended: false }));




// 保护所有需要认证的路由
app.use((req, res, next) => {
    // 检查请求路径是否在白名单中
    const path = req.path;
    const isWhitelisted = whiteApi.some(pattern => {
        // 如果 pattern 是正则表达式，则使用它来测试 path
        const regex = new RegExp(pattern);
        return regex.test(path);
    });

    if (isWhitelisted) {
        next(); // 白名单路径，不需要认证，直接调用 next 中间件
    } else {
        expressjwt({
            secret: 'ultraman',
            algorithms: ['HS256']
        })(req, res, next); // 非白名单路径，进行JWT认证
    }
});

// 指定静态资源目录
app.use(express.static('public'));
app.use('/uploadFiles', express.static('uploadFiles'));

// 引入路由模块
const router = require('./router/index');
// 注册路由模块
app.use(router);

// 错误中间件
app.use((err, req, res, next) => {
    if (err.status === 404) {
        res.status(404).json({
            code: 404,
            message: err.message || 'Not Found'
        });
    } else {
        res.status(500).json({
            code: 500,
            message: err.message || 'Internal Server Error'
        });
    }
});

// 创建 HTTPS 服务器
// https.createServer(HTTPS_OPTIONS, app).listen(3000, () => {
//   console.log('server running at https://wangmiao888.com:3000，服务器地址');
// });

app.listen(3000, () => {
    console.log('Server is running');
});